import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.junit.Test;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class fileUploadDemo {

    // jc提供的SecretId
    public static String SECRET_ID = "100002";
    // jc提供的SecretKey
    public static String SECRET_KEY = "2a4afaf10a0ebd926dc91387373a0594";



    public static String SERVICE_HOST = "127.0.0.1:8080";

    public static String SERVICE_URL = "http://" + SERVICE_HOST + "/jc-order/fileUpload/v1/upload";


    @Test
    public void testFileUpload() throws ParseException {

        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {

            // 2. 生成签名
            SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
            String now = format.format(new Date());
            String rawData =SECRET_ID + now + SECRET_KEY;
            String signature= DigestUtils.md5Hex(rawData);

            // 3. 创建HTTP请求
            HttpPost httpPost = new HttpPost(SERVICE_URL);

            // 4. 设置签名头
            httpPost.setHeader("secretId", SECRET_ID);
            httpPost.setHeader("timestamp", now);
            httpPost.setHeader("sign", signature);

            // 5. 构建文件上传内容
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.addBinaryBody(
                    "file",
                    new File("C:\\Users\\panxin\\OneDrive\\图片\\企业微信截图_20250515143421.png"),
                    ContentType.IMAGE_JPEG,
                    "test.jpg"
            );


            HttpEntity multipart = builder.build();
            httpPost.setEntity(multipart);

            // 7. 执行请求
            HttpResponse response = httpClient.execute(httpPost);

            // 8. 处理响应
            int statusCode = response.getStatusLine().getStatusCode();
            String responseBody = EntityUtils.toString(response.getEntity());

            System.out.println("Status Code: " + statusCode);
            System.out.println("Response: " + responseBody);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
